from flask import Flask, request, render_template, jsonify
from dotenv import load_dotenv
import os
from datetime import datetime
import time
from utils.qwen_client import analyze_with_qwen
from pathlib import Path


# 加载 .env 文件
def load_environment():
    """明确加载环境变量"""
    # 确定 .env 文件路径
    env_path = Path(__file__).parent / '.env'
    print(f"Looking for .env at: {env_path}")
    
    if env_path.exists():
        print(".env file found, loading...")
        load_dotenv(dotenv_path=env_path, override=True)
        
        # 打印所有相关的环境变量
        env_vars = ['API_BASE_URL', 'API_TOKEN', 'MINIO_ACCESS_KEY',  'OLLAMA_MODEL']
        
        print("Environment variables from .env:")
        for var in env_vars:
            value = os.getenv(var)
            if value:
                print(f"  {var}: {value}")
            else:
                print(f"  {var}: NOT SET")
                
    else:
        print(".env file not found!")

# 在Hydra之前加载环境变量
load_environment()

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/data/tmp/'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 限制上传大小为16MB

# 允许上传的图片格式
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 模拟大模型识别函数（实际项目中替换为真实模型调用）
def call_ai_model(image_path):
    # 这里模拟处理时间
    # time.sleep(2)
    MODEL_TYPE = os.getenv("OLLAMA_TYPE")
    MODEL_HOST = os.getenv("OLLAMA_HOST")
    MODEL = os.getenv("OLLAMA_MODEL")
    
    result = analyze_with_qwen(MODEL_TYPE,[image_path],MODEL_HOST,MODEL,0)
    print(f"qwen result: {result}")
    return result

@app.route('/')
def index():
    return render_template('index2.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '没有选择文件'})
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'})
    
    if file and allowed_file(file.filename):
        # 生成时间戳文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"temp_{timestamp}.jpeg"
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        # 保存文件
        file.save(filepath)
        
        # 调用大模型（模拟）
        results = call_ai_model(filepath)
        
        return jsonify({
            'success': True,
            'filename': filename,
            'detection_result': results
        })
    
    return jsonify({'error': '不支持的文件格式'})

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=5001)